﻿using System;
using System.Web;
using System.Web.Caching;
using Eneta.Portal.Common;
using Eneta.Portal.Forum.Core.Domain.Entities;
using Microsoft.SharePoint;

namespace Eneta.Portal.Forum.Core.Service.Application
{
    public sealed class ForumApplication
    {
        // Fields
        //private static readonly ForumApplication instance = new ForumApplication();

        // Methods
        private ForumApplication()
        {
            Title = "Discussion Forums";
        }

        public string GetDefaultGroupsForNewUser()
        {
            return "1;2";
        }

        public string GetLink(SharePointForumControls action)
        {
            return string.Format("{0}?control={1}", BasePath, action);
        }

        public string GetLink(SharePointForumControls action, string format, params object[] args)
        {
            return string.Format("{0}?control={1}&{2}", BasePath, action, string.Format(format, args));
        }

        public string GetNewTopicLink(int forumId, string postMethod)
        {
            return GetLink(SharePointForumControls.UpdateMessage, "forum={0}&{1}={2}", new object[] { forumId, "postmethod", postMethod });
        }

        public string GetReplyLink(int topicId, string postMethod)
        {
            return Instance.GetLink(SharePointForumControls.UpdateMessage, "topic={0}&{1}={2}", new object[] { topicId, "postmethod", postMethod });
        }

        public SPUser AppPoolUser { get; set; }
        public string BasePath { get; set; }
        public string ClassResourcePath { get; set; }

        public ForumUser CurrentUser
        {
            get
            {
                if (SpUser == null)
                    return null;
                return RepositoryRegistry.ForumUserRepository.GetBySharePointId(SpUser.ID);
            }
        }

        public Cache ForumCache { get; set; }

        public string ForumImage
        {
            get
            {
                return string.Format("{0}/{1}", "/_layouts/images/", "COMACT.GIF");
            }
        }

        public static ForumApplication Instance
        {
            get
            {
                if (HttpContext.Current.Items["ForumApplication"] != null)
                    return (ForumApplication)HttpContext.Current.Items["ForumApplication"];

                var instance = new ForumApplication();

                HttpContext.Current.Items["ForumApplication"] = instance;
                HttpContext.Current.ApplicationInstance.EndRequest += ApplicationInstanceEndRequest;
                return instance;
            }
        }

        static void ApplicationInstanceEndRequest(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            if (context == null)
                return;

            if (context.Items["ForumApplication"] == null)
                return;

            var app = (ForumApplication) context.Items["ForumApplication"];
            if(app.SpWeb != null)
                try
                {
                    var site = app.SpWeb.Site;
                    app.SpWeb.Dispose();
                    site.Dispose();
                }
                catch(Exception ex)
                {
                    Logger.LogWarning("ApplicationInstanceEndRequest: Error when disposing forum objects",
                                      "ForumApplication");
                    Logger.LogException(ex);
                }
            context.Items.Remove("ForumApplication");
        }

        public SPUser SpUser { get; set; }
        public SPWeb SpWeb { get; set; }
        public string Title { get; set; }
    }
}
